<?php
/**
 * sec osm project 
 * 
 * @final
 * @package lilyenglish
 * @version $Id:$
 */
class MyClass_Action extends Zend_Controller_Action {

	protected $_user = NULL;
	protected $_smarty = NULL;
	protected $_dbAdapter = NULL;
	protected $_set = NULL;
	
	public function commonAction() {
		
		$this->controller = $this->getRequest ()->getControllerName ();
		$this->action = $this->getRequest ()->getActionName ();
		$this->view->controller=$this->controller;
		$this->view->action=$this->action;

		$this->view->isNoHead =0;
	
		$this->_dbAdapter = Zend_Registry::get('db');

		if($this->controller != 'login' && $this->controller!='error' && $this->action!='auto'){
					
			$this->_user = $this->checkLogin ();
			$this->view->_user=$this->_user;

			$user_can_action=explode(',',$this->_user->action_list);
			//if(!in_array($this->controller,$user_can_action) && $this->controller != 'index')
				//$this->_redirect ( '/' );
			
//			$this->view->user_can_action=$user_can_action;	
			//获取顶部菜单
			 
			$menulist=$this->_dbAdapter->fetchAll('select menuid,menu,menu_en,istopbar,fathermenu from menu where ishidden=0 order by fathermenu asc,orderby desc');
			$action_list=$this->_dbAdapter->fetchOne('select action_list from admin_central where id='.$this->_user->id);
			$action=explode(',',$action_list);   
			$menuarray=array();
			 if($menulist){       
				 foreach($menulist as $key => $value){
					 if($value['istopbar']==1 && in_array($value['menuid'], $action)){
						   $menuarray[$value['menuid']]=$value['menu'] ;
					  }
					$menusonss[$value['fathermenu']][]=$value;  	
					$link=explode('/',$value['menu_en']);
					if(is_array($link) && isset($link[1])){
						if( $this->controller == $link[1] && $value['fathermenu']>0)	 
							 $this->view->activefather=$value['fathermenu'];
						else
							 $this->view->activefather=$value['menuid'];
					}
				 }
				$this->view->menuarray=$menuarray;	  
				$this->view->menusonss=$menusonss;	  
				  
			}  
			 
		}
 
		$this->setting=$this->_dbAdapter->fetchPairs('select variable,value from setting');
		$this->view->setting=$this->setting;
	}
	 
	 
	/**
	* 子数据库的链接
	*/
	public function getDbLink($groupid=0) {
		
		$groupid=intval(trim($groupid));
		if(!$groupid)
			return -1;
			
		$sql='select dbhost,dbusername,dbpassword,dbname from groups where groupid="'.$groupid.'"';
		$result=$this->_dbAdapter->fetchRow($sql);
		
		if(!$result)
			return -2;
			
		$dbArray['host']=$result['dbhost'];
		$dbArray['username']=$result['dbusername'];
		$dbArray['password']=$this->authcode($result['dbpassword'],'DECODE','mactop');
		$dbArray['dbname']=$result['dbname'];	 
		$dbArray['charset']='utf8';	 
		$groupdbAdapter = Zend_Db::factory ( "PDO_MYSQL",$dbArray );
		$groupdbAdapter->getProfiler ()->setEnabled ( true );
	//	$groupdbAdapter->query ( 'set names utf8');
		unset($dbArray);
		//Zend_Registry::set('groupdbdb', $groupdbAdapter);
		return $groupdbAdapter;
	}
		
		
	public function getDbCache($filename) {
		//$dbcache = $this->_config->dbcache->toArray ();
		$dirname = PROJECT_ROOT . $this->_config->dbcache->dir;
		
		$file_name = $dirname . '/' . $filename . '.php';
		//print_r($file_name );
		if(file_exists($file_name))
			$arrayRes = include $file_name;
		else
			$arrayRes =array();	
			
		return $arrayRes;
	}
	

	public function isPost() {
		return $this->_request->isPost ();
	}
	
	public function getParam($key, $default = NULL) {
		return $this->_getParam ( $key, $default );
	}
	
	public function checkLogin() {
		$auth = Zend_Auth::getInstance ();
		if (! $auth->hasIdentity ()) {
			return $this->_redirect ( '/login' );
		}
		$userinfo=$auth->getIdentity();
		if(!isset($userinfo->id) || empty($userinfo->id))
			return $this->_redirect ( '/login' );
		
		return $userinfo;
	}

	public function isAllowed($res, $priv, $extra = true) {
		if (is_NULL ( $res )) {
			$request = $this->getRequest ();
			$res = $request->getModuleName ();
			$res .= '_' . $request->getControllerName ();
			$res .= '_' . $this->getRequest ()->getActionName ();
		}
		$result = $this->_user->isAllowed ( $res, $priv, $extra );
		return $result;
	}
	
	public function feedback($messgae, $title, $backUrl = 'javascript:window.history.back()', $icon = 'note',$delay=3) {
			$param = array ('message' => $messgae, 'title' => $title, 'url' => $backUrl, 'icon' => $icon ,'delay'=>$delay);
			$this->_forward ( 'message', 'error', '', $param );
	}
	
	public function log($message){        
		$log=Zend_Registry::get("logger");
		$log->setEventItem('modules', $this->_request->getModuleName() );
		$log->setEventItem('controller', $this->_request->getControllerName() );
		$log->setEventItem('action', $this->_request->getActionName() );
		$log->log($message,8);
		//使用方法	$this->log(var_export($course, true));
	}
	 
	public function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
             
        $ckey_length = 4;  
    
        $key = md5($key ? $key : 'mactop');
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16)); 
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
    
        $cryptkey = $keya.md5($keya.$keyc);
        //echo $cryptkey;exit;
        $key_length = strlen($cryptkey); 
    
        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
        
        $string_length = strlen($string);
        
        $result = '';
        $box = range(0, 255); 
    
        $rndkey = array();
        for($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
    
        for($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp; 
        }
    
        for($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
    
        if($operation == 'DECODE') {
            if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc.str_replace('=', '', base64_encode($result));
        }
    }   
	 
	
	//1内容，2模版，3类别表示
	public function whtml($data=array(),$type='advertorial',$canhtml=0,$groupid=0,$dbname=''){
			 if(!is_array($data))
				return -1; 
			if(!isset($data['id']))
				return -2;

		$replaceArr=array('headtitle','title','content','time','imgurl','address','start_time','end_time','sign_up_start_time','sign_up_end_time');

		//$type=($type=='advertorial')?'advertorial':'events';
		if($type=='events')
			$url='htmlmode/2.html';
		elseif($type=='advertorial'){
			$url='htmlmode/1.html';
		}elseif($type=='calendar'){
			$url='htmlmode/calendar.html';
		}elseif($type=='privacy'){
			$url='htmlmode/privacy.html';
		}else{
			return -3;
		}
		
		
		$content = file_get_contents($url);     //读取模板文件的内容   
		if($content){   
			foreach($replaceArr as $key => $value){
				
				if($value=='content'){
					if(isset($data[$value]) && $canhtml==0){
						$data[$value]=strip_tags($data[$value]);
						$data[$value]=str_replace(' ','&nbsp;',$data[$value]);
						$data[$value]=str_replace("\n",'</p>'."\n".'<p class="text">',$data[$value]);
						$data[$value]='<p class="text">'.$data[$value].'</p>';
						if(isset($data[$value]))
  
							if(strlen($data[$value])>600){
							$a=strpos(@$data[$value],'</p>',600);
 
							}
						else
							$a=0;
						if($a){
							$subcontent=substr($data[$value],0,$a-1);
							$data[$value]=str_replace($subcontent,$subcontent.'<!--$$$-->',$data[$value]);					
						}
					}
				}
				
				if(isset($data[$value]))
					$content = str_replace('{'.$value.'}',$data[$value],$content);   
			}
		}
		if($groupid==0 && $dbname==''){
			file_put_contents('html/privacy.html',$content);   //将替换后的内容写进html文件中  
		}
		else{ 
			file_put_contents('html/'.$groupid.'/'.$type.'_'.$dbname.'_'.$data['id'].'.html',$content);   //将替换后的内容写进html文件中  
		}
	 }
	 
	    

	public function check_remote_file_exists($url)
	{
		$curl = curl_init($url);
		// 不取回数据
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); //不加这个会返回403，加了才返回正确的200，原因不明
		// 发送请求
		$result = curl_exec($curl);
		$found = false;
		// 如果请求没有发送失败
		if ($result !== false)
		{
		// 再检查http响应码是否为200
		$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		if ($statusCode == 200)
		{
		$found = true;
		}
		}
		curl_close($curl);
		
		return $found;
	}
	public function get($url, $refer)
	{
		$info = null;
		$ch = curl_init($url);
		$options = array(
				CURLOPT_RETURNTRANSFER => true,         // return web page
				CURLOPT_HEADER         => false,        // don't return headers
				CURLOPT_FOLLOWLOCATION => true,         // follow redirects
				CURLOPT_ENCODING       => "",           // handle all encodings
				CURLOPT_USERAGENT      => "",     // who am i
				CURLOPT_AUTOREFERER    => true,         // set referer on redirect
				CURLOPT_CONNECTTIMEOUT => 120,          // timeout on connect
				CURLOPT_TIMEOUT        => 120,          // timeout on response
				CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
				CURLOPT_SSL_VERIFYHOST => 0,            // don't verify ssl
				CURLOPT_SSL_VERIFYPEER => false,        //
				//CURLOPT_COOKIEFILE     =>$this->cookiefilepath,
				//CURLOPT_COOKIEJAR      =>$this->cookiefilepath,
				CURLOPT_REFERER        =>$refer,
		);
		curl_setopt_array($ch, $options);
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}
	
	/**
	 * 生成缩略图	等比例缩小
	 * @param $srcfile
	 * @param $thumbfile
	 * @param $thumbwidth
	 * @param $thumbheight
	 * @param $flag	0为按传入参数压缩	1:程序自动判断，2宽度为准，3高度为准 4 按参数裁切取中间内容 
	 * @return int
	 */
	public function ThumbRatio($srcfile, $thumbfile, $thumbwidth, $thumbheight, $flag = 1) {
		
		if (! ($attachinfo = @getimagesize ( $srcfile ))) {
			return 0;
		}
		
		$srcPhoto = NULL;
		$imagefunc = '';
		switch ($attachinfo ["mime"]) {
			case "image/jpeg" :
				$srcPhoto = imagecreatefromjpeg ( $srcfile );
				$imagefunc = 'imagejpeg';
				break;
			case 'image/gif' :
				$srcPhoto = imagecreatefromgif ( $srcfile );
				$imagefunc = 'imagegif';
				break;
			case 'image/png' :
				$srcPhoto = imagecreatefrompng ( $srcfile );
				$imagefunc = 'imagepng';
				break;
		}
		

		//	$this->log('|||||||||||||||||||||||||||||||||||||||||||||||||||!!!!!!!@@@@@');
		list ( $img_w, $img_h ) = $attachinfo;
		
		/******/
		//载入图片x坐标
		$src_x = 0;
		//载入图片y坐标
		$src_y = 0;
		/******/
		
		$exif = exif_read_data($srcfile);

		//  $this->log('---------Orientation==================='.$exif['Orientation']);
		$isrotate=0;
		if(!empty($exif['Orientation'])) {
			 
			switch($exif['Orientation']) { 
			case 8: 
				$srcPhoto = imagerotate($srcPhoto,90,0); 
				$isrotate=1;
				$a=$img_w;
				$img_w=$img_h;
				$img_h=$a;
				break; 
			case 3: 
				$srcPhoto = imagerotate($srcPhoto,180,0); 
				$isrotate=1;
				break; 
			case 6: 
				$srcPhoto = imagerotate($srcPhoto,-90,0); 
				$isrotate=1;
				$a=$img_w;
				$img_w=$img_h;
				$img_h=$a;
				break; 
			} 
		} 
		
		//$img_w,$img_h原图高宽度
		if ($img_h <= $thumbheight && $img_w <= $thumbwidth) {
			
			if($isrotate==1){
				$thumb_photo = imagecreatetruecolor ( $img_h, $img_h );
				@imageCopyreSampled ( $thumb_photo, $srcPhoto, 0, 0, 0, 0, $img_h, $img_h, $img_w, $img_h );
				if ($attachinfo ['mime'] == 'image/jpeg') {
					$imagefunc ( $thumb_photo, $thumbfile, 100 );
				} else {
					$imagefunc ( $thumb_photo, $thumbfile );
				}
				ImageDestroy ( $srcPhoto );
			}else
				copy ( $srcfile, $thumbfile );
			
			return 1;
		}
		

		if ($flag == 1) {
			if ($img_w > $thumbwidth || $img_h > $thumbheight) {
				$x_ratio = $thumbwidth / $img_w;
				$y_ratio = $thumbheight / $img_h;				
				if (($x_ratio * $img_h) < $thumbheight) {
					$temp_height = ceil ( $x_ratio * $img_h );
					$temp_width = $thumbwidth;
				} else {
					$temp_width = ceil ( $y_ratio * $img_w );
					$temp_height = $thumbheight;
				}
			} else {
				$temp_width = $img_w;
				$temp_height = $img_h;
			}
				
		} elseif ($flag == 2) {
			$temp_width = $thumbwidth;
			$temp_height = $img_h / ($img_w / $thumbwidth);
		} elseif ($flag == 3) {
			$temp_height = $thumbheight;
			$temp_width = $img_w / ($img_h / $thumbheight);
		}elseif ($flag == 4) {
			$width_y=$img_w;
			$height_y=$img_h;
			
			/******/
			//计算载入图片的x坐标
			$src_x = $thumbwidth >= $thumbheight ? 0 : round(abs(($thumbwidth - $thumbheight)/2));
			//计算载入图片的y坐标
			$src_y = $thumbwidth >= $thumbheight ? round(abs(($thumbheight - $thumbwidth)/2)) : 0;
			/******/
			
			if($width_y>$height_y){//如果宽大于高
				$width_y_y=$height_y;
				$height_y_y=$height_y;
				$jq_x=($width_y-$height_y)/2;
				$jq_y=0;
			}else if($width_y<$height_y){//如果宽小于高
				$height_y_y=$width_y;
				$width_y_y=$width_y;
				$jq_x=0;
				$jq_y=($height_y-$width_y)/2;
			}else if($width_y=$height_y){//如果宽小于高
				$width_y_y=$width_y;
				$height_y_y=$height_y;
				$jq_x=0;
				$jq_y=0;
			}
			$temp_width  = $thumbwidth;
			$temp_height = $thumbheight;
			// $img_w  = $width_y_y;
			// $img_h  = $height_y_y;
			/******/
			//$img_w = $img_w >= $img_h ? $img_w : $img_h;
			//$img_h = $img_h > $img_w ? $img_h : $img_w;
			/******/
			// $this->log( $img_w.'%'.$img_h .'@'. $temp_width .'!'.$temp_height);
			// 640%640@130!80
		} else{
			$temp_width =$thumbwidth;
			$temp_height=$thumbheight;
		}
		$thumb_photo = imagecreatetruecolor ( $temp_width, $temp_height );
		//设置目标图片的宽高
		if($flag == 4) {
			//当宽度大于等于高度时 则等于宽度 否则 等于高度 为了让宽高相等 适应最大边
			$temp_width = $thumbwidth >= $thumbheight ? $thumbwidth : $thumbheight;
			//同上 宽高改变
			$temp_height = $thumbheight > $thumbwidth ? $thumbheight : $thumbwidth;
		}

		@imageCopyreSampled ( $thumb_photo, $srcPhoto, 0, 0, $src_x, $src_y, $temp_width, $temp_height, $img_w, $img_h );
		if ($attachinfo ['mime'] == 'image/jpeg') {
			$imagefunc ( $thumb_photo, $thumbfile, 100 );
		} else {
			$imagefunc ( $thumb_photo, $thumbfile );
		}
		ImageDestroy ( $srcPhoto );
		return 1;
	}



   /**
	* 推送信息方法
	*/
	public function push_message($type,$schoolid=0,$classid=0,$uid=0,$isstudent=1,$wantsenttime=0) {
		//$this->buildDbAdapter('centraldb');
		$timenow=time();
		if(!$wantsenttime)
			$wantsenttime=$timenow;
		if($isstudent){//学生 phone
			//article
			if($type=='article'){
				$content="孩子的班级动态更新了。 Check out new blog please!";
				$this->_dbAdapter->query('insert push_student_content (`uid`,`token`,`contenttype`,`content`,`addtime`,`wantsenttime`) select uid,token,"'.$type.'","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_student_token where  uid in ('.$uid.')');
				$this->log('insert push_student_content (`uid`,`token`,`contenttype`,`content`,`addtime`,`wantsenttime`) select uid,token,"'.$type.'","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_student_token where  uid in ('.$uid.')');
			}//end article	
			
			
			/*
			//食谱
			if($type=='menu'){
				if(!$schoolid)
					return -1;
				$sql='select uid from student where schoolid='.$schoolid;
				$uidlist=$this->_dbAdapter->fetchCol($sql);
				if($uidlist){
					$content="孩子的新食谱公布了。 The menu is updated.";
					$this->_dbAdapter->query('insert push_student_content (`uid`,`contenttype`,`content`,`addtime`,`wantsenttime`) select distinct uid,"menu","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_student_token where  uid in ('.implode(',',$uidlist).')');
				}
			}//end menu
			elseif($type=='event'){
				if(!$schoolid)
					return -1;
				$sql='select uid from student where schoolid='.$schoolid;
				$uidlist=$this->_dbAdapter->fetchCol($sql);
				if($uidlist){
					$content="有新活动了，快去报名。 There is a new event.";
					$this->_dbAdapter->query('insert push_student_content (`uid`,`contenttype`,`content`,`addtime`,`wantsenttime`) select distinct uid,"event","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_student_token where  uid in ('.implode(',',$uidlist).')');
				}
			}//end event
			elseif($type=='advertorial'){
				if(!$schoolid)
					return -1;
				$sql='select uid from student where schoolid='.$schoolid;
				$uidlist=$this->_dbAdapter->fetchCol($sql);
				if($uidlist){
					$content="教育资讯有新内容了。 New educational information published.";
					$this->_dbAdapter->query('insert push_student_content (`uid`,`contenttype`,`content`,`addtime`,`wantsenttime`) select distinct uid,"info","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_student_token where  uid in ('.implode(',',$uidlist).')');
				}
			}//end advertorial	
			*/		
			elseif($type=='notice'){
				if(!$classid)
					return -1;

				$content="有新通知了。 Check out new notices please.";

				$sql='select uid from student_class_v where classid='.$classid;
				$uidlist=$this->_dbAdapter->fetchCol($sql);
				if($uidlist){
					$this->_dbAdapter->query('insert push_student_content (`uid`,`contenttype`,`content`,`addtime`,`wantsenttime`) select distinct uid,"notice","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_student_token where  uid in ('.implode(',',$uidlist).')');
				}
			}//end notice			
			
		}else{//class pad
		

			/*
			if($type=='notice'){
				if(!$classid)
					return -1;

				$content="学校发布新通知了。 Check out new notices please.";

				$sql='select uid from class where classid='.$classid;
				$uid=$this->_dbAdapter->fetchOne($sql);
				if($uid){
				$this->_dbAdapter->query('insert push_class_content (`uid`,`token`,`contenttype`,`content`,`addtime`,`wantsenttime`) select uid,token,"'.$type.'","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_class_token where uid='.$uid);
				}
			}//end notice	
			*/
			if($type=='letter'){
				//$haveuid=$this->_dbAdapter->fetchOne('select uid from push_class_token where uid="'.$uid.'"');
				if(!$haveuid)
					return -100;
				
				$content="有一条新消息了。Have a new message.";

				$this->_dbAdapter->query('insert push_class_content (`uid`,`token`,`contenttype`,`content`,`addtime`,`wantsenttime`) select uid,token,"'.$type.'","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_class_token where uid='.$uid);
				$this->log('insert push_class_content (`uid`,`token`,`contenttype`,`content`,`addtime`,`wantsenttime`) select uid,token,"'.$type.'","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_class_token where uid='.$uid);
			}//end letter		


			if($type=='credit'){
				$haveuid=$this->_dbAdapter->fetchOne('select uid from push_class_token where uid="'.$uid.'"');
				if(!$haveuid)
					return -100;


				$content="积分增加了。";
				$this->_dbAdapter->query('insert push_class_content (`uid`,`token`,`contenttype`,`content`,`addtime`,`wantsenttime`) select uid,token,"'.$type.'","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_class_token where uid='.$uid);
			}//end credit		
				/*
			if($type=='creditshop'){
				if(!$classid)
					return -1;

				$content="积分商城增加了。";

				$sql='select uid from class where classid='.$classid;
				$uid=$this->_dbAdapter->fetchOne($sql);
				if($uid){
				$this->_dbAdapter->query('insert push_class_content (`uid`,`token`,`contenttype`,`content`,`addtime`,`wantsenttime`) select uid,token,"'.$type.'","'.$content.'","'.$timenow.'","'.$wantsenttime.'" from push_class_token where uid='.$uid);
				}
			}//end creditshop	
				*/
		}
	}
	
		  /*
	获取年龄 传入 yyyy-mm-dd 类型的年月日
	*/
	 public function getAge($birthday){
	 	$birthday=getDate(strtotime($birthday));   
		if(!is_array($birthday))
			return 0;

		$now=getDate();
		
		$month=0;
		if($now['mon']>$birthday['mon'])
			$month=1;
		if($now['mon']==$birthday['mon'])	
			if($now['mday']>=$birthday['mday'])
				$month=1;
		if($now['year']-$birthday['year']+$month>100)
			return 0;
			
		return $now['year']-$birthday['year']+$month;
	 }
	 
}
